package com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.send.file;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.cetccloud.ap.config.ProxyConfig;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Config;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.S30Exception;
import com.cetccloud.ap.util.IdUtil;
import com.thunisoft.exchange.gateway.protocol.GatewayProtocol;
import com.thunisoft.exchange.gateway.protocol.file.GatewayFileDest;
import com.thunisoft.exchange.gateway.protocol.file.GatewayFileMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName FileHandler
 * @Description TODO
 * @Author superz
 * @Date 2021/4/24 21:32
 * @Version 1.0
 **/
@Slf4j
@Component("sendFileXmlHandler")
public class FileXmlHandler {

    @Autowired
    private ProxyConfig proxyConfig;

    @Autowired
    private S30Config s30Config;

    public List<String> handle(List<String> destAppIds, String fileUrl, long fileSize) throws S30Exception {
        GatewayFileMessage msg = new GatewayFileMessage();
        msg.setDataSrc(s30Config.getProxy().getAppId());
        msg.setDataSec(s30Config.getProxy().getSec());
        msg.setDataUrl(fileUrl);
        msg.setDataSize(fileSize);
        // 是否需要回应标志位（0表示不需要回应，1表示需要回应）
        msg.setDataRespFlag(s30Config.getProxy().getRespFlag());

        List<String> msgIdList = new ArrayList<>();
        destAppIds.stream().forEach(destAppId -> {
            String msgId = StringUtils.EMPTY;
            if ("1".equals(s30Config.getProxy().getRespFlag())) {
                msgId = IdUtil.msgId();
                msgIdList.add(msgId);
            }
            msg.addDataDst(new GatewayFileDest(destAppId, msgId));
        });

        try {
            JSONObject body = new JSONObject();
            body.put("fileName", fileUrl);
            body.put("content", GatewayProtocol.encodeFileMessage(msg));
            log.info("调用文件传输接口生成xml文件[{}]", fileUrl);
            HttpRequest.post(proxyConfig.getFile().getCaiji())
                    .body(body.toJSONString())
                    .execute();
        } catch (Exception e) {
            log.error("调用文件传输接口生成xml文件[{}]失败", fileUrl ,e);
        }
        return msgIdList;
    }
}
